<template>
    <!-- 富文本 -->
    <div>
        <editor
            v-model="content"
            :init="init"
            :disabled="disabled"
            @showContent="showContent"
        ></editor>
    </div>
</template>

<script>
import tinymce from "tinymce/tinymce";
import Editor from "@tinymce/tinymce-vue";
import "tinymce/themes/silver/theme";
import "tinymce/icons/default/icons";
import "tinymce/plugins/link";
import "tinymce/plugins/code";
import "tinymce/plugins/table";
import "tinymce/plugins/lists";
import "tinymce/plugins/print";
import "tinymce/plugins/contextmenu";
import "tinymce/plugins/wordcount";
import "tinymce/plugins/colorpicker";
import "tinymce/plugins/textcolor";
import "tinymce/plugins/fullscreen";
import "tinymce/plugins/autosave";
import "tinymce/plugins/paste";
import "tinymce/plugins/image";
import "tinymce/plugins/imagetools";
export default {
    components: {
        Editor,
    },
    props: {
        value: {
            type: String,
            default: "",
        },
        disabled: {
            type: Boolean,
            default: false,
        },
        height: {
            type: [Number, String],
            required: false,
            default: 780,
        },
        plugins: {
            type: [String, Array],
            default:
                "preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr nonbreaking insertdatetime advlist lists wordcount imagetools textpattern autosave bdmap lineheight print",
            // "link code table lists wordcount ",
        },
        toolbar: {
            type: [String, Array],
            default:
                // "link code table wordcount | alignleft aligncenter alignright alignjustify outdent indent formatpainter | formatselect | fontselect | fontsizeselect | bullist numlist |",
                "code undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link codesample | alignleft aligncenter alignright alignjustify outdent indent lineheight formatpainter | \
      styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \
      table image media charmap hr pagebreak insertdatetime | bdmap fullscreen preview  print",
        },
    },
    data() {
        return {
            //初始化配置
            init: {
                language_url: "/ywxt/static/tinymce/langs/zh_CN.js",
                language: "zh_CN",
                skin_url: "/ywxt/static/tinymce/skins/ui/oxide",
                content_css:
                    "/ywxt/static/tinymce/skins/content/document/content.css",
                height: this.height,
                min_height: this.height,
                // max_height: this.height,
                object_resizing: false, //禁用表格内联样式拖拽拉伸
                table_resize_bars: false, //禁用表格单元格拖拽拉伸
                toolbar_mode: "wrap",
                plugins: this.plugins,
                toolbar: this.toolbar,
                content_style: "p {margin: 5px 0;}", //内容样式
                fontsize_formats:
                    "12px 14px 16px 18px 22px 24px 36px 48px 56px 72px",
                font_formats:
                    "微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;",
                branding: false, //不显示富文本支持方
                contextmenu:
                    "undo redo | cut copy paste pastetext | selectall table", // 富文本右键菜单
                // 解决粘贴图片后，不自动上传，而是使用base64编码。
                /*urlconverter_callback: (url, node, onSave, name) => {
                    if (node === "img" && url.startsWith("blob:")) {
                        // Do some custom URL conversion
                        console.log("urlConverter:", url, node, onSave, name);
                        tinymce.activeEditor &&
                            tinymce.activeEditor.uploadImages();
                    }
                    // Return new URL
                    return url;
                },*/
                // 此处为图片上传处理函数
                images_upload_handler: (
                    blobInfo,
                    success
                    // failure,
                    // progress
                ) => {
                    // 方法1：用base64的图片形式上传图片
                    const img = "data:image/jpeg;base64," + blobInfo.base64();
                    success(img);

                    /*// 方法2：上传oos
                    const xhr = new XMLHttpRequest();
                    xhr.withCredentials = false;
                    xhr.open("POST", "/zuul/purchase/manage/object/push");
                    // xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=utf-8')
                    xhr.setRequestHeader("x-token", this.$store.getters.token);
                    xhr.upload.onprogress = function (e) {
                        progress((e.loaded / e.total) * 100);
                    };
                    xhr.onload = function () {
                        if (xhr.status === 403) {
                            failure("HTTP Error: " + xhr.status, {
                                remove: true,
                            });
                            return;
                        }
                        if (xhr.status < 200 || xhr.status >= 300) {
                            failure("HTTP Error: " + xhr.status);
                            return;
                        }
                        const json = JSON.parse(xhr.responseText);
                        if (!json || typeof json.data.fileName !== "string") {
                            failure("Invalid JSON: " + xhr.responseText);
                            return;
                        }

                        const file = json.data;
                        const url =
                            "/purchase/manage/attachment/public/operation/pull?path=" +
                            file.fileName +
                            "&fileName=" +
                            encodeURIComponent(file.originalFileName);
                        success(url);
                    };

                    xhr.onerror = function () {
                        failure(
                            "Image upload failed due to a XHR Transport error. Code: " +
                                xhr.status
                        );
                    };

                    const formData = new FormData();
                    formData.append(
                        "multipartFile",
                        blobInfo.blob(),
                        blobInfo.filename()
                    );

                    xhr.send(formData);*/
                },
            },
            content: this.value,
        };
    },
    mounted() {
        tinymce.init({});
    },
    methods: {
        showContent(message) {
            console.log(message);
        },
        handleImgUpload(blobInfo, success, failure) {
            console.log(blobInfo + "+" + success + "+" + failure);
        },
    },
    watch: {
        value(newValue) {
            this.content = newValue;
        },
        content(newValue) {
            this.$emit("showContent", newValue);
        },
    },
};
</script>
<style scoped lang="scss"></style>
